package com.zhhtech.zhh.utils

import com.zhhtech.zhh.ui.AppCore
import java.io.File
import java.math.BigDecimal


object GlideCatchUtil {

    // 获取Glide磁盘缓存大小
    fun getCacheSize() = kotlin.runCatching {
        getFormatSize(getFolderSize(AppCore.app.cacheDir).toDouble())
    }.getOrDefault("获取失败")

    // 获取指定文件夹内所有文件大小的和
    private fun getFolderSize(file: File): Long {
        return kotlin.runCatching {
            var size: Long = 0
            file.listFiles().forEach { subFile ->
                size += if (subFile.isDirectory) {
                    getFolderSize(subFile)
                } else {
                    subFile.length()
                }
            }
            size
        }.getOrDefault(0)
    }

    // 格式化单位
    private fun getFormatSize(size: Double): String {
        val kiloByte = size / 1024
        if (kiloByte < 1) {
            return size.toString() + "Byte"
        }
        val megaByte = kiloByte / 1024
        if (megaByte < 1) {
            val result1 = BigDecimal(kiloByte.toString())
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString().toString() + "KB"
        }
        val gigaByte = megaByte / 1024
        if (gigaByte < 1) {
            val result2 = BigDecimal(megaByte.toString())
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString().toString() + "MB"
        }
        val teraBytes = gigaByte / 1024
        if (teraBytes < 1) {
            val result3 = BigDecimal(gigaByte.toString())
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString().toString() + "GB"
        }
        val result4 = BigDecimal(teraBytes)
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString().toString() + "TB"
    }

    // 清除Glide磁盘缓存，自己获取缓存文件夹并删除方法
    fun cleanCatchDisk(): Boolean {
        return deleteFolderFile(AppCore.app.cacheDir, true)
    }

    // 按目录删除文件夹文件方法
    private fun deleteFolderFile(file: File, deleteThisPath: Boolean): Boolean {
        return try {
            if (file.isDirectory) {
                val files = file.listFiles()
                for (file1 in files) {
                    deleteFolderFile(file1, true)
                }
            }
            if (deleteThisPath) {
                if (!file.isDirectory) {
                    file.delete()
                } else {
                    if (file.listFiles().isEmpty()) {
                        file.delete()
                    }
                }
            }
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }
}